package com.Ying.ECG;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.os.Build;
import android.content.Intent;
import android.widget.Toast;
import android.util.Log;
import java.util.UUID;
import java.util.HashMap;
import java.util.List;
import com.unity3d.player.UnityPlayerActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;

public class MainActivity extends UnityPlayerActivity
{
    private static final int REQUEST_COARSE_LOCATION = 0;

    private BluetoothAdapter bluetoothAdapter;
    private CheckBluetoothListener checkBluetootnCallback;
    private BluetoothScanListener scanCallback;
    private LeScanCallback scanListener;
    private HashMap<String, BluetoothDevice> btDeviceDic;
    private BluetoothGattCallback gattCallback;
    private GetErrorListener getErrorCallback;
    private HashMap<String, BluetoothGatt> gattDic;

	@Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        btDeviceDic = new HashMap();
        gattDic = new HashMap();
    }

    public void CheckBluetooth(CheckBluetoothListener callback)
    {
        checkBluetootnCallback = callback;
        if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) 
        {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
        mayRequestLocation();
    }

    public void SetGetErrorListener(GetErrorListener callback)
    {
        getErrorCallback = callback;
    }

    private void mayRequestLocation() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                //判断是否需要 向用户解释，为什么要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION))
                    Toast.makeText(this, "动态请求权限", Toast.LENGTH_LONG).show();
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_COARSE_LOCATION);
                return;
            } else {

            }
        } else {

        }
    }
    //系统方法,从requestPermissions()方法回调结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        //确保是我们的请求
        if (requestCode == REQUEST_COARSE_LOCATION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "权限被授予", Toast.LENGTH_SHORT).show();
            } else if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) 
        {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "蓝牙已经开启", Toast.LENGTH_SHORT).show();
                checkBluetootnCallback.OnResult(true);
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "蓝牙未开启", Toast.LENGTH_SHORT).show();
                checkBluetootnCallback.OnResult(false);
                finish();
            }
        }
    }

    public void StartScan(BluetoothScanListener callback)
    {
        if(scanListener != null){ return; }
        scanCallback = callback;
        scanListener = new LeScanCallback()
        {
            @Override
            public void onLeScan(BluetoothDevice device, int arg1, byte[] arg2) 
            {
                String deviceName = device.getName();
                if(deviceName == null || btDeviceDic.containsKey(deviceName)) { return; }
                btDeviceDic.put(deviceName, device);
                scanCallback.OnGetName(deviceName);
            }
        };
        bluetoothAdapter.startLeScan(scanListener);
        Toast.makeText(this, "开启扫描", Toast.LENGTH_SHORT).show();
    }

    public void StopScan()
    {
        bluetoothAdapter.stopLeScan(scanListener);
    }

    public void Connect(String deviceName, GetDataListener callback)
    {
        BluetoothDevice device = btDeviceDic.get(deviceName);
        if(device == null)
        {
            Toast.makeText(this, "未找到该蓝牙设备", Toast.LENGTH_SHORT).show();
            return;
        }
        gattCallback = new BluetoothGattCallback() 
        {
            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) 
            {
                if (newState == BluetoothGatt.STATE_CONNECTED) 
                {
                    Log.e("BT", "设备连接上 开始扫描服务");
                    gatt.discoverServices();
                }
                if (newState == BluetoothGatt.STATE_DISCONNECTED) 
                {
                    String name = gatt.getDevice().getName();
                    if(gattDic.containsKey(name)){ gattDic.remove(name); }
                    gatt.close();
                    // 连接断开
                    /*连接断开后的相应处理*/      
                }
            }

            @Override
            public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) 
            {
                super.onCharacteristicWrite(gatt, characteristic, status);
            }

            @Override
            public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) 
            {
                
            }

            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) 
            {
                List<BluetoothGattService> servers = gatt.getServices();
                boolean isHave = false;
                for(int i = 0;i < servers.size();i++)
                {
                    if(getErrorCallback != null){ getErrorCallback.GetError(0, servers.get(i).getUuid().toString()); }
                    if(servers.get(i).getUuid().toString().equals("00001809-0000-1000-8000-00805f9b34fb"))
                    {
                        isHave = true;
                        BluetoothGattCharacteristic characteristic = servers.get(i).getCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"));
                        gatt.setCharacteristicNotification(characteristic,true);
                        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        gatt.writeDescriptor(descriptor);
                    }
                    else if(servers.get(i).getUuid().toString().equals("0783b03e-8535-b5a0-7140-a304d2495cb7"))
                    {
                        isHave = true;
                        BluetoothGattCharacteristic characteristic2 = servers.get(i).getCharacteristic(UUID.fromString("0783b03e-8535-b5a0-7140-a304d2495cb9"));
                        characteristic2.setValue(new byte[]{0x05});
                        gatt.writeCharacteristic(characteristic2);
                        BluetoothGattCharacteristic characteristic = servers.get(i).getCharacteristic(UUID.fromString("0783b03e-8535-b5a0-7140-a304d2495cb8"));
                        gatt.setCharacteristicNotification(characteristic,true);
                        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        gatt.writeDescriptor(descriptor);
                    }
                }
                if(!isHave)
                {
                    if(getErrorCallback != null){ getErrorCallback.GetError(2, gatt.getDevice().getName()); }
                }
            }

            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) 
            {
                if(characteristic.getUuid().toString().equals("00002a1c-0000-1000-8000-00805f9b34fb"))
                {
                    byte[] data = characteristic.getValue();
                    callback.GetData(0, data);
                    Log.e("BT", "信息长度" + data.length);
                }
                else if(characteristic.getUuid().toString().equals("0783b03e-8535-b5a0-7140-a304d2495cb8"))
                {
                    byte[] data = characteristic.getValue();
                    callback.GetData(1, data);
                    Log.e("BT", "信息长度" + data.length);
                }
            }
        };
        BluetoothGatt g = device.connectGatt(this, false, gattCallback);
        gattDic.put(deviceName, g);
    }

    public void DisconnectDevice(String name)
    {
        if(!gattDic.containsKey(name)){ return; }
        BluetoothGatt g = gattDic.get(name);
        gattDic.remove(name);
        g.disconnect();
        g.close();
    }
}